package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Service
public class C2VersionsService {

    @Autowired
    private DruidDataSource druidDataSource;

    /**
     * 获取版本信息，按时间倒序排序返回计划版本、释放版本和发布版本的 versionNo 集合
     *
     * @return Map<String, String> 包含计划版本、释放版本和发布版本的 versionNo 集合
     */
    public Map<String, String> getVersionData() {
        // SQL 查询语句，按 updateTime 倒序排列
        String sql = "SELECT " +
                "GROUP_CONCAT(versionNo ORDER BY buildTime DESC) AS totalVersions, " +
                "GROUP_CONCAT(CASE WHEN releaseStatus IN (1, 2, 7) THEN versionNo END ORDER BY buildTime DESC) AS releasedVersions, " +
                "GROUP_CONCAT(CASE WHEN pubStatus IN (0, 2) THEN versionNo END ORDER BY buildTime DESC) AS publishedVersions " +
                "FROM c2_version_info;";

        // 存储查询结果的 Map
        Map<String, String> versionData = new HashMap<>();

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            if (rs.next()) {
                // 获取查询结果并放入 Map 中
                String totalVersions = rs.getString("totalVersions");
                String releasedVersions = rs.getString("releasedVersions");
                String publishedVersions = rs.getString("publishedVersions");

                // 将结果填充到 Map
                versionData.put("totalVersions", totalVersions);
                versionData.put("releasedVersions", releasedVersions);
                versionData.put("publishedVersions", publishedVersions);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return versionData;
    }
}
